import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { 
  Card, 
  Spin, 
  Alert, 
  Button, 
  Row, 
  Col, 
  Tag, 
  Space, 
  Modal, 
  Form, 
  Input, 
  Select, 
  InputNumber
} from 'antd';
import { 
  FaTasks, 
  FaPlay, 
  FaStop, 
  FaSync, 
  FaPlus,
  FaSearch,
  FaFilter
} from 'react-icons/fa';
import { motion } from 'framer-motion';
import { crawlerApi, CrawlerJob } from '../../../services/crawlerApi';
import { useAuthStore } from '../../../stores/authStore';
import { useThemeStore } from '../../../stores/themeStore';
import { getTheme } from '../../../theme/config';
import CustomTable from '../../../components/custom/CustomTable';
import CustomCard from '../../../components/custom/CustomCard';
import type { ColumnsType } from 'antd/es/table';
import { notification } from '../../../components/common';

const { Option } = Select;

interface CreateJobForm {
  name: string;
  description: string;
  crawler_type: string;
  start_urls: string;
  concurrent_requests: number;
  download_delay: number;
}

const CrawlerTasksPage: React.FC = () => {
  const navigate = useNavigate();
  const { isAuthenticated } = useAuthStore();
  const { mode } = useThemeStore();
  const theme = getTheme(mode);
  const [loading, setLoading] = useState(true);
  const [creating, setCreating] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [jobs, setJobs] = useState<CrawlerJob[]>([]);
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [createForm] = Form.useForm<CreateJobForm>();

  // 检查认证状态
  useEffect(() => {
    if (!isAuthenticated) {
      navigate('/login');
    }
  }, [isAuthenticated, navigate]);

  // 获取爬虫任务列表
  useEffect(() => {
    const fetchJobs = async () => {
      try {
        setLoading(true);
        setError(null);
        
        const jobsData = await crawlerApi.getCrawlerJobs(0, 100);
        setJobs(jobsData);
      } catch (err) {
        console.error('获取爬虫任务失败:', err);
        setError('获取爬虫任务失败: ' + (err instanceof Error ? err.message : '未知错误'));
      } finally {
        setLoading(false);
      }
    };

    if (isAuthenticated) {
      fetchJobs();
    }
  }, []); // 空依赖数组确保只在组件挂载时执行一次

  // 刷新任务列表
  const refreshJobs = async () => {
    try {
      setLoading(true);
      const jobsData = await crawlerApi.getCrawlerJobs(0, 100);
      setJobs(jobsData);
    } catch (err) {
      notification.error({
        title: '刷新失败',
        message: '刷新失败: ' + (err instanceof Error ? err.message : '未知错误')
      });
    } finally {
      setLoading(false);
    }
  };

  // 创建爬虫任务
  const handleCreateJob = async (values: CreateJobForm) => {
    try {
      setCreating(true);
      
      // 将start_urls字符串转换为数组
      const startUrls = values.start_urls
        .split('\n')
        .map(url => url.trim())
        .filter(url => url.length > 0);
      
      // 构建设置对象
      const settings: Record<string, any> = {};
      if (values.concurrent_requests) {
        settings.CONCURRENT_REQUESTS = values.concurrent_requests;
      }
      if (values.download_delay) {
        settings.DOWNLOAD_DELAY = values.download_delay;
      }
      
      await crawlerApi.createCrawlerJob({
        name: values.name,
        description: values.description,
        crawler_type: values.crawler_type,
        start_urls: startUrls,
        settings: settings
      });
      
      notification.success({
        title: '任务创建',
        message: '任务创建成功'
      });
      setCreateModalVisible(false);
      createForm.resetFields();
      refreshJobs();
    } catch (err) {
      notification.error({
        title: '创建失败',
        message: '创建任务失败: ' + (err instanceof Error ? err.message : '未知错误')
      });
    } finally {
      setCreating(false);
    }
  };

  // 获取状态标签颜色
  const getStatusColor = (status: string) => {
    switch (status) {
      case 'pending': return 'default';
      case 'running': return 'processing';
      case 'completed': return 'success';
      case 'failed': return 'error';
      case 'cancelled': return 'warning';
      default: return 'default';
    }
  };

  // 表格列定义
  const columns: ColumnsType<CrawlerJob> = [
    {
      title: '任务名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string) => (
        <span style={{ color: theme.textPrimary, fontWeight: 'bold' }}>{text}</span>
      )
    },
    {
      title: '类型',
      dataIndex: 'crawler_type',
      key: 'crawler_type',
      render: (type: string) => (
        <Tag color={type === 'scrapy' ? 'blue' : type === 'mechanicalsoup' ? 'green' : 'purple'}>
          {type}
        </Tag>
      )
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag color={getStatusColor(status)}>{status}</Tag>
      )
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (date: string) => new Date(date).toLocaleString()
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="primary" 
            size="small"
            icon={<FaPlay />}
            onClick={() => notification.info({
              title: '功能待实现',
              message: '启动任务功能待实现'
            })}
          >
            启动
          </Button>
          <Button 
            danger 
            size="small"
            icon={<FaStop />}
            onClick={() => notification.info({
              title: '功能待实现',
              message: '停止任务功能待实现'
            })}
          >
            停止
          </Button>
        </Space>
      )
    }
  ];

  // 获取卡片样式
  const getCardStyle = () => ({
    background: theme.cardBackground,
    border: `1px solid ${theme.cardBorder}`,
    borderRadius: '12px',
    boxShadow: mode === 'light' ? theme.cardShadow : 'none'
  });

  if (!isAuthenticated) {
    return null;
  }

  return (
    <div style={{ padding: '24px', color: theme.textPrimary }}>
      <motion.div
        initial={{ opacity: 0, y: -20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.5 }}
      >
        <div style={{ marginBottom: '24px' }}>
          <h1 style={{ 
            color: theme.glowColor, 
            fontSize: '28px',
            fontWeight: 'bold',
            marginBottom: '8px'
          }}>
            <FaTasks style={{ marginRight: '12px' }} />
            爬虫任务管理
          </h1>
          <p style={{ 
            fontSize: '16px',
            opacity: 0.8,
            marginBottom: '24px',
            color: theme.textSecondary
          }}>
            创建和管理爬虫任务
          </p>
        </div>

        {/* 操作栏 */}
        <div style={{ 
          marginBottom: '24px',
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          flexWrap: 'wrap',
          gap: '12px'
        }}>
          <div>
            <motion.div whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }}>
              <Button 
                type="primary" 
                icon={<FaPlus />}
                onClick={() => setCreateModalVisible(true)}
              >
                创建任务
              </Button>
            </motion.div>
            <motion.div whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }} style={{ display: 'inline-block', marginLeft: '12px' }}>
              <Button 
                icon={<FaSync />}
                onClick={refreshJobs}
              >
                刷新
              </Button>
            </motion.div>
          </div>
          
          <div style={{ display: 'flex', gap: '12px' }}>
            <Input 
              placeholder="搜索任务..."
              prefix={<FaSearch style={{ color: theme.textSecondary }} />}
              style={{ width: '200px', background: theme.cardBackground, border: `1px solid ${theme.cardBorder}` }}
            />
            <motion.div whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }}>
              <Button icon={<FaFilter />}>
                筛选
              </Button>
            </motion.div>
          </div>
        </div>

        {/* 任务列表 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5, delay: 0.2 }}
        >
          <CustomCard>
            {error ? (
              <Alert
                message="错误"
                description={error}
                type="error"
                showIcon
                style={{ marginBottom: '16px' }}
              />
            ) : null}
            
            {loading ? (
              <div style={{ textAlign: 'center', padding: '40px' }}>
                <Spin size="large" tip="加载中..." />
              </div>
            ) : (
              <CustomTable 
                dataSource={jobs}
                columns={columns}
                rowKey="job_id"
                pagination={{
                  pageSize: 10,
                  showSizeChanger: true,
                  showQuickJumper: true
                }}
                locale={{
                  emptyText: (
                    <div style={{ padding: '40px', textAlign: 'center', color: theme.textSecondary }}>
                      <FaTasks style={{ fontSize: '48px', marginBottom: '16px', opacity: 0.5, color: theme.glowColor }} />
                      <p>暂无爬虫任务</p>
                      <p style={{ fontSize: '14px' }}>
                        点击"创建任务"按钮开始创建爬虫任务
                      </p>
                    </div>
                  )
                }}
              />
            )}
          </CustomCard>
        </motion.div>

        {/* 创建任务模态框 */}
        <Modal
          title={
            <div style={{ display: 'flex', alignItems: 'center', color: theme.textPrimary }}>
              <FaPlus style={{ marginRight: '8px', color: theme.glowColor }} />
              创建爬虫任务
            </div>
          }
          open={createModalVisible}
          onCancel={() => {
            setCreateModalVisible(false);
            createForm.resetFields();
          }}
          onOk={() => createForm.submit()}
          confirmLoading={creating}
          width={600}
          styles={{ 
            body: { 
              background: theme.contentBackground,
              color: theme.textPrimary
            },
            header: {
              background: theme.cardBackground,
              borderBottom: `1px solid ${theme.cardBorder}`
            }
          }}
        >
          <Form
            form={createForm}
            layout="vertical"
            onFinish={handleCreateJob}
          >
            <Form.Item
              name="name"
              label={<span style={{ color: theme.textPrimary }}>任务名称</span>}
              rules={[{ required: true, message: '请输入任务名称' }]}
            >
              <Input 
                placeholder="请输入任务名称" 
                style={{ background: theme.cardBackground, border: `1px solid ${theme.cardBorder}`, color: theme.textPrimary }}
              />
            </Form.Item>
            
            <Form.Item
              name="description"
              label={<span style={{ color: theme.textPrimary }}>任务描述</span>}
            >
              <Input.TextArea 
                placeholder="请输入任务描述" 
                rows={3} 
                style={{ background: theme.cardBackground, border: `1px solid ${theme.cardBorder}`, color: theme.textPrimary }}
              />
            </Form.Item>
            
            <Form.Item
              name="crawler_type"
              label={<span style={{ color: theme.textPrimary }}>爬虫类型</span>}
              rules={[{ required: true, message: '请选择爬虫类型' }]}
            >
              <Select 
                placeholder="请选择爬虫类型"
                style={{ background: theme.cardBackground, border: `1px solid ${theme.cardBorder}`, color: theme.textPrimary }}
              >
                <Option value="scrapy">Scrapy</Option>
                <Option value="mechanicalsoup">MechanicalSoup</Option>
                <Option value="scrapyd">Scrapyd</Option>
              </Select>
            </Form.Item>
            
            <Form.Item
              name="start_urls"
              label={<span style={{ color: theme.textPrimary }}>起始URLs</span>}
              rules={[{ required: true, message: '请输入起始URLs，每行一个' }]}
            >
              <Input.TextArea 
                placeholder="请输入起始URLs，每行一个" 
                rows={4}
                style={{ fontFamily: 'monospace', background: theme.cardBackground, border: `1px solid ${theme.cardBorder}`, color: theme.textPrimary }}
              />
            </Form.Item>
            
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="concurrent_requests"
                  label={<span style={{ color: theme.textPrimary }}>并发请求数</span>}
                >
                  <InputNumber 
                    min={1} 
                    max={100} 
                    placeholder="默认16"
                    style={{ width: '100%', background: theme.cardBackground, border: `1px solid ${theme.cardBorder}`, color: theme.textPrimary }}
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="download_delay"
                  label={<span style={{ color: theme.textPrimary }}>下载延迟(秒)</span>}
                >
                  <InputNumber 
                    min={0} 
                    max={10} 
                    step={0.1}
                    placeholder="默认1"
                    style={{ width: '100%', background: theme.cardBackground, border: `1px solid ${theme.cardBorder}`, color: theme.textPrimary }}
                  />
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </Modal>
      </motion.div>
    </div>
  );
};

export default CrawlerTasksPage;